package org.jxc.service;

import java.util.List;
import java.util.Set;

import org.hibernate.SessionFactory;
import org.jxc.dao.OutOrderDAO;
import org.jxc.domain.OutOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.team4.dao.DAOFactory;
import org.team4.domain.RoleUsers;
import org.team4.domain.Users;
import org.team4.exception.CRUDException;
import org.team4.service.IService;
import org.team4.util.LoginBean;
import org.team4.vo.Page;

public class OutOrderService implements IService {

	private OutOrderDAO outOrderDAO;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		outOrderDAO = (OutOrderDAO) DAOFactory.getDAO(sessionFactory,
				OutOrderDAO.class);
	}

	public Page<OutOrder> listPagination(Page<OutOrder> page)
			throws CRUDException {
		Users user = LoginBean.getLoginBean().getUser();
		Set<RoleUsers> set = user.getRoleUsers();
		boolean flag = false;
		for (RoleUsers ru : set) {
			if (ru.getRole().getName().equals("库存管理员")) {
				flag = true;
			}
		}
		if (flag) {
			return outOrderDAO
					.pagination(
							page,
							"from OutOrder where deleteFlag='0' and auditState=1",
							null);
		} else {
			if (user.getDepartment().getManager().getId().equals(user.getId())) {
				return outOrderDAO.pagination(page,
						"from OutOrder where deleteFlag = '0'",
						"createTime desc");
			} else {
				return outOrderDAO.pagination(page,
						"from OutOrder where deleteFlag = '0'"
								+ " and creator.id= '" + user.getId() + "'",
						"createTime desc");
			}
		}
	}

	public OutOrder findBySalesOrderId(String salesOrderId)
			throws CRUDException {
		List<OutOrder> temp = outOrderDAO.find(
				"from OutOrder where deleteFlag = '0' "
						+ " and salesOrder.id = '" + salesOrderId + "'", null);
		if (temp != null && !temp.isEmpty()) {
			return temp.get(0);
		}
		return null;
	}

	public void save(OutOrder order) throws CRUDException {
		outOrderDAO.save(order);
	}

	public OutOrder findById(String id) throws CRUDException {
		return outOrderDAO.get(id);
	}

	public void update(OutOrder object) throws CRUDException {
		outOrderDAO.update(object);
	}

	public void delete(String id) throws CRUDException {
		OutOrder object = outOrderDAO.get(id);
		object.setDeleteFlag("1");
		outOrderDAO.update(object);
	}

	public void delByOutOrderId(String id) {
		// TODO Auto-generated method stub

	}

}
